<template>
  <div class="container">
    <ul class="tab_header">
      <li :class="active == '1' || '2'?'active':''">1、基础设置</li>
      <li :class="active == '2'?'active':''">2、排课计划</li>
    </ul>
    <!-- 基础设置 -->
    <div class="form-box" v-if="active == '1'">
      <div class="header_Top">
        <p>当前班级：
          <span>{{className}}</span>
        </p>
        <p>班主任：
          <span>{{teacherName}}</span>
        </p>
      </div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="开课日期" prop="startDate">
          <el-date-picker
            v-model="ruleForm.startDate "
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            @change="changeDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="开课时间" :rules="{required: true, message: '域名不能为空', trigger: 'blur' }"></el-form-item>
        <el-form-item
          v-for="(domain, index) in ruleForm.domains"
          :key="domain.key"
          :prop="'domains.' + index + '.value'"
          :rules="{required: true, message: '开课时间不能为空', trigger: 'blur' }"
        >
          <el-select
            v-model="thisWeekDayArr[index]"
            @change="changeDateToweekIndex(index,thisWeekDayArr[index])"
            style="width:20%;float:left;"
          >
          <!-- <el-option
              value="请选择"
            ></el-option> -->
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <span
            style="height:22px;width:2px;float:left;background:blue;display:block;margin:5px 5px 0 5px "
          ></span>
          <el-input style="width:20%" v-model="domain.value" placeholder="00:00"></el-input>
          <el-button @click.prevent="removeDomain(domain)">X</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="addDomain">添加</el-button>
        </el-form-item>
        <el-form-item label="排课方式" prop="resource">
          <el-radio-group v-model="ruleForm.resource">
            <el-radio label="静态排课"></el-radio>
            <el-radio label="动态排课"></el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="ruleForm.resource == '静态排课'">
          <el-form-item label="上课教室" prop="teachClassId">
            <el-select v-model="ruleForm.teachClassId" placeholder="请选择">
              <el-option
                v-for="(item,index) in classData"
                :key="index"
                :label="item.name||' '"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="授课教师" prop="region">
            <el-select v-model="ruleForm.region" placeholder="请选择">
              <el-option
                v-for="(item,index) in organizationArr"
                :key="index"
                :label="item.name"
                :value="item.organizationUserId"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-if="ruleForm.resource == '动态排课'">
          <p class="Dynamic_Text">动态排课，请在[排课计划]中根据班级具体排课计划安排授课教师、教室</p>
        </template>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">下一步，创建课表</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 排课计划 -->
    <div v-if="active == '2'">
      <course-plan
        :classList="classData"
        :teacherList="organizationArr"
        @editCourse="editActive"
        :status="status"
      ></course-plan>
    </div>
  </div>
</template>
<script>
import coursePlan from "./coursePlan";
import store from '@/store'
export default {
  name: "baseform",
  data: function() {
    return {
      options: [
        {
          value: "1",
          label: "星期一"
        },
        {
          value: "2",
          label: "星期二"
        },
        {
          value: "3",
          label: "星期三"
        },
        {
          value: "4",
          label: "星期四"
        },
        {
          value: "5",
          label: "星期五"
        },
        {
          value: "6",
          label: "星期六"
        },
        {
          value: "7",
          label: "星期日"
        }
      ],
      value: "",
      active: "1",
      ruleForm: {
        startDate: "",
        region: "",
        resource: "静态排课",
        teachClassId: "",
        domains: [
          {
            value: "",
            region2: ""
          }
        ],
      },
      rules: {
        startDate: [
          { required: true, message: "请选择开课日期", trigger: "change" }
        ],
        region: [
          { required: true, message: "请选择授课教师", trigger: "change" }
        ],
        resource: [
          { required: true, message: "请选择活动资源", trigger: "change" }
        ],
        teachClassId: [{ required: true, message: "请选择教室", trigger: "blur" }]
      },
      default_val:"请选择",
      teachClassId: "",
      organizationArr: [],
      teacherName: "",
      className: "",
      tableData: [],
      classData: [],
      thisWeekDayArr: [""],
      status: 0,
      getLessionDatas:this.$store.state,
      ClassId:this.$route.query.id,
      weekTimeList:this.$store.commit("getLessionData"),
      arr:[],
      organizationUserId:""
      
    };
  },
  components: {
    coursePlan
  },
  created() {
    this.ClassroomAjax();
  },
  watch: {
    $route() {
      if (this.$route.path == "/home/RowCourse") {
        this.teachClassId = this.$route.query.id;
        this.status = this.$route.query.status;
        if (this.status == "1") {
          this.active = 2;
        }else{
          this.active = 1;
        }
        this.className = this.$route.query.name;
        if (this.teachClassId) {
          this.selectChanelAjax();
        }
        this.getData();
      }
    }
  },
  methods: {
    getLession(){
      if(this.status == 1){
        var that = this;
        let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
        this.url = "/api/course/xzs/lessionPlanRule.info.get";
        this.$axios({
          url:this.url,
          method:"post",
          data:{  
              teachClassId:Number(this.ClassId)
          },
          transformRequest: [
              function(data) {
                  let ret = "";
                  for (let it in data) {
                  ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
                  }
                  return ret;
              }     
          ]
      }).then(res =>{
          this.lessionPlanData=res.data.data
          this.$store.commit("getLessionData",res.data.data)
          that.ruleForm.teachClassId = this.lessionPlanData.classroomId
          this.timeOut=this.timestampToTime(this.lessionPlanData.lessionBeginTime)
          that.ruleForm.startDate = this.timeOut;
          that.ruleForm.region = this.lessionPlanData.organizationUserId
          var arr = JSON.parse(this.lessionPlanData.weekTimeList)
          arr.forEach(element => {
            
          });
          this.ruleForm.domains[0].value = arr[0].hour+":"+arr[0].minute+"0"
          if(arr[0].week == "1"){
            arr[0].week ="一"
          }else if(arr[0].week == "2"){
            arr[0].week ="二"
          }else if(arr[0].week == "3"){
            arr[0].week ="三"
          }else if(arr[0].week == "4"){
            arr[0].week ="四"
          }else if(arr[0].week == "5"){
            arr[0].week ="五"
          }else if(arr[0].week == "6"){
            arr[0].week ="六"
          }else if(arr[0].week == ""){
            arr[0].week ="日"
          }
          this.thisWeekDayArr[0] =  "星期"+arr[0].week;
          
          if(this.status == 0){
            that.ruleForm.teachClassId = " "
            that.ruleForm.region = " "
          }
      }).catch(err =>{
          console.log(err);
      })
      }else{
        return
      }
    },
    //时间戳转换
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      var Y = date.getFullYear() + "-";
      var M =(date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      var D = date.getDate() + " ";
      var h = date.getHours() + ":";
      var m = String(date.getMinutes()).padStart(2, "0");
      return Y + M + D + h + m;
    },
    changeDateToweekIndex(index,val) {
      console.log(index,val)
      this.ruleForm.domains[index].region2 = val;
    },
    changeDate(e){
      let WeekArray = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"];
      let WeekDate = new Date(String(e)).getDay()//这个 
      let weekDayIndex = WeekDate==0?7:WeekDate;
      this.thisWeekDayArr = [WeekArray[weekDayIndex-1]];
      this.ruleForm.domains[0].region2 = weekDayIndex;
    },  
    // 切换
    handleChange(index) {
      if (this.$route.params.type != 1) {    //在哪
        this.active = index;
      }
    },
    submitForm(formName) {
      console.log(this.ruleForm);
      console.log(this.ruleForm.region);
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.$refs[formName].validate(valid => {
        if (valid) {
          let weekTimeList = [];
          if (this.ruleForm.domains && this.ruleForm.domains.length > 0) {
            this.ruleForm.domains.forEach(item => {
              console.log(item);
              weekTimeList.push({
                week: Number(item.region2),
                hour: Number(item.value.split(":")[0]),
                minute: Number(item.value.split(":")[1])
              });//
            });
          }
          const data = {
            teachClassId: Number(this.teachClassId),
            lessionBeginTime: this.ruleForm.startDate.split(" ")[0]||this.ruleForm.startDate,
            weekTimeList: weekTimeList,
            classroomId: Number(this.ruleForm.teachClassId),
            organizationUserId: Number(this.ruleForm.region)
          };    
          console.log(this.ruleForm.region)
          this.$axios({
            url: "/api/course/xzs/lessions.plan",
            method: "post",
            data
          }).then(res => {
            if(this.status == 1){
              this.$confirm('你将要更改排课规则。点击确定，将清空当前排课数据，重新进行排课?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                  }).then(() => {
                    if (res.data.value == "成功") {
                      this.active = 2;
                      this.$message.success("基础信息保存成功");
                    } else {
                      this.$message.error(res.data.value);
                    }
                  }).catch(() => {
              });
            }else if(this.status == 0){
              if (res.data.value == "成功") {
                this.active = 2;
                this.$message.success("基础信息保存成功");
              } else {
                this.$message.error(res.data.value);
              }
            }
          });
        }
      });
    },
    addDomain() {
      this.ruleForm.region2 = "";
      this.ruleForm.domains.push({
        value: "",
        key: Date.now()
      });
      this.thisWeekDayArr.push("")
    },
    // 删除
    removeDomain(item) {
      var index = this.ruleForm.domains.indexOf(item);
      if (index !== -1) {
        this.ruleForm.domains.splice(index, 1);
      }
    },
    // 获取 教室 列表
    ClassroomAjax() {
      this.url = "/api/user/xzs/classroom.list.get";
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          organizationId: organizationId
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          }
        ] 
      })
        .then(res => {
          this.classData = res.data.data;
          // console.log(this.classData);
        })
        .catch(err => {});
    },
    // 获取教师列表
    selectChanelAjax() {
      this.url = "/api/user/xzs/organizationUser.list.get";
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          organizationId: organizationId
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ]
      })
        .then(res => {
          this.organizationArr = res.data.data;
          this.$nextTick(() => {
            this.organizationArr.forEach(item => {
              if (item.organizationUserId == item.organizationUserId) {
                this.teacherName = item.name;
                // if(this.status == 1){
                //   this.ruleForm.region = item.organizationUserId
                // }
              } 
            });
          });
        })
        .catch(err => {});
    },
    // 获取教室列表
    getData() {
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      var that = this;
      this.url = "/api/user/xzs/teachClass.list.get";
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          organizationId: organizationId
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ]
      })
        .then(res => {
          this.tableData = res.data.data;
          // console.log(this.tableData)
        })
        .catch(err => {});
    },
    editActive(val) {
      this.active = val;
    }
  },
  mounted() {
    this.teachClassId = this.$route.query.id;
    this.className = this.$route.query.name;
    this.status = this.$route.query.status;
    if (this.status == "1") {
      this.active = 2;
    } else {
      this.active = 1;
    }
    if (this.teachClassId) {
      this.selectChanelAjax();
    }
    this.getLession();   //获取下一个界面传来的值
    this.getData();
  }
};
</script>
<style>
.header_Top {
  width: 100%;
  text-indent: 30px;
  margin-bottom: 20px;
  float: left;
}
.header_Top p {
  float: left;
}
.tab_header {
  width: auto;
  height: 50px;
  list-style: none;
  margin-bottom: 50px;
}
.tab_header li {
  width: 300px;
  height: 50px;
  line-height: 50px;
  font-size: 16px;
  text-align: center;
  position: relative;
  float: left;
  background: #fff;
  border: 1px solid #6474d3;
  box-sizing: border-box;
  color: #6474d3;
  margin-right: 15px;
  border-right: none;
}
.tab_header .active {
  background: #6474d3;
  border-color: #6474d3;
  color: #fff;
}
.tab_header li:after {
  position: absolute;
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-top: 23px solid transparent;
  border-bottom: 23px solid transparent;
  border-left: 13px solid #fff;
  left: 299px;
  top: 2px;
  left: 299px;
  top: 2px;
}
.tab_header li:before {
  position: absolute;
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-top: 25px solid transparent;
  border-bottom: 25px solid transparent;
  border-left: 15px solid #6474d3;
  left: 299px;
}
.tab_header .active {
  background: #6474d3;
}
.tab_header .active:after {
  border-top: 25px solid transparent;
  border-bottom: 25px solid transparent;
  border-left: 15px solid #6474d3;
  left: 299px;
  top: -1px;
}
.Dynamic_Text {
  height: 10.8vh;
  line-height: 10.8vh;
  text-align: center;
  margin-bottom: 3vh;
  background: rgb(242, 242, 242);
}
</style>